package com.atguigu.guli.service.oss.controller;

import com.atguigu.guli.service.base.exception.GuliException;
import com.atguigu.guli.service.base.result.R;
import com.atguigu.guli.service.base.result.ResultCodeEnum;
import com.atguigu.guli.service.oss.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Api(tags = "阿里云文件管理")
@CrossOrigin//跨域
@RestController
@RequestMapping("/admin/oss/file")
public class FileController {

    @Autowired
    FileService fileService;
//    处理上传文件,上传方式必须是post方式,因为文件要找请求体内提交(get提交方式1.有容量限制2.存在urlEncoding,会造成数据丢失)


    @ApiOperation("文件上传")
    @PostMapping("upload")
    public R uploadFile(
            @ApiParam(value = "模块名称",required = true)
            @RequestParam("module") String module,
            @ApiParam(value = "上传文件",required = true)
            @RequestParam("file") MultipartFile file){//存储的参数 1. 存储文件的目录 2.文件表单项
        //    处理文件上传
        String path = null;
        try {
            path = fileService.uploadFile(module,file);

        } catch (Exception e) {
//            自定义异常
            System.out.println("==============异常抛出");
            throw new GuliException(ResultCodeEnum.FILE_UPLOAD_ERROR);
        }

        return R.ok().data("path",path);
    }


    //    处理文件删除
    @ApiOperation("文件删除")
    @DeleteMapping("delete")
    public R deleteFile(
            @ApiParam(value = "模块名称", required = true)
            @RequestParam("module") String module,
            @RequestParam String path) {//存储的参数 1. 存储文件的目录 2.文件表单项

        fileService.deleteFile(module, path);
        return R.ok().message("删除成功");
    }


    //    处理文件批量删除
    @ApiOperation("文件批量删除")
    @DeleteMapping("batchDelete")
    public R batchDeleteFile(
            @ApiParam(value = "模块名称", required = true)
            @RequestParam("module") String module,
            @RequestBody List<String> paths) {//存储的参数 1. 存储文件的目录 2.文件表单项

        fileService.batchDeleteFile(module, paths);
        return R.ok().message("批量删除成功");
    }


}
